<template>
  <div class="form-preview">
    <!-- 头部工具栏 -->
    <div class="preview-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回编辑</el-button>
        <div class="form-info">
          <h3>{{ formData.title || '未命名表单' }}</h3>
          <el-tag v-if="formData.status === 0" type="info">草稿</el-tag>
          <el-tag v-if="formData.status === 1" type="success">发布中</el-tag>
          <el-tag v-if="formData.status === 2" type="danger">已关闭</el-tag>
        </div>
      </div>
      <div class="header-right">
        <el-button icon="Link" @click="copyFormLink" v-if="formData.status === 1">复制链接</el-button>
        <el-button icon="Edit" @click="editForm">编辑表单</el-button>
      </div>
    </div>

    <!-- 预览内容 -->
    <div class="preview-content">
      <div class="form-container">
        <!-- 表单头部 -->
        <div class="form-header">
          <h1>{{ formData.title || '未命名表单' }}</h1>
          <p v-if="formData.description" class="form-description">{{ formData.description }}</p>
        </div>

        <!-- 表单字段 -->
        <div class="form-fields">
          <div v-if="formData.fields.length === 0" class="empty-form">
            <el-icon :size="64"><DocumentAdd /></el-icon>
            <p>此表单暂无字段</p>
            <el-button type="primary" @click="editForm">添加字段</el-button>
          </div>
          
          <el-form v-else :model="formModel" :rules="formRules" ref="formRef" label-position="top">
            <div 
              v-for="field in formData.fields" 
              :key="field.id"
              class="field-item"
              :class="{ 
                'field-half': field.width === 'half',
                'field-third': field.width === 'third'
              }"
            >
              <!-- 文本输入 -->
              <el-form-item 
                v-if="field.type === 'text' || field.type === 'email' || field.type === 'phone'"
                :label="field.label" 
                :required="field.required"
                :prop="`field_${field.id}`"
              >
                <el-input 
                  v-model="formModel[`field_${field.id}`]"
                  :placeholder="field.placeholder"
                  :maxlength="field.maxLength"
                />
                <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
              </el-form-item>

              <!-- 多行文本 -->
              <el-form-item 
                v-else-if="field.type === 'textarea'"
                :label="field.label" 
                :required="field.required"
                :prop="`field_${field.id}`"
              >
                <el-input 
                  v-model="formModel[`field_${field.id}`]"
                  type="textarea"
                  :placeholder="field.placeholder"
                  :maxlength="field.maxLength"
                  :rows="4"
                />
                <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
              </el-form-item>

              <!-- 数字输入 -->
              <el-form-item 
                v-else-if="field.type === 'number'"
                :label="field.label" 
                :required="field.required"
                :prop="`field_${field.id}`"
              >
                <el-input-number 
                  v-model="formModel[`field_${field.id}`]"
                  :placeholder="field.placeholder"
                  :min="field.min"
                  :max="field.max"
                />
                <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
              </el-form-item>

              <!-- 单选题 -->
              <el-form-item 
                v-else-if="field.type === 'radio'"
                :label="field.label" 
                :required="field.required"
                :prop="`field_${field.id}`"
              >
                <el-radio-group v-model="formModel[`field_${field.id}`]">
                  <el-radio 
                    v-for="option in field.options" 
                    :key="option.value"
                    :label="option.value"
                  >
                    {{ option.label }}
                  </el-radio>
                </el-radio-group>
                <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
              </el-form-item>

              <!-- 多选题 -->
              <el-form-item 
                v-else-if="field.type === 'checkbox'"
                :label="field.label" 
                :required="field.required"
                :prop="`field_${field.id}`"
              >
                <el-checkbox-group v-model="formModel[`field_${field.id}`]">
                  <el-checkbox 
                    v-for="option in field.options" 
                    :key="option.value"
                    :label="option.value"
                  >
                    {{ option.label }}
                  </el-checkbox>
                </el-checkbox-group>
                <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
              </el-form-item>

              <!-- 下拉选择 -->
              <el-form-item 
                v-else-if="field.type === 'select'"
                :label="field.label" 
                :required="field.required"
                :prop="`field_${field.id}`"
              >
                <el-select 
                  v-model="formModel[`field_${field.id}`]"
                  :placeholder="field.placeholder"
                >
                  <el-option 
                    v-for="option in field.options" 
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
                <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
              </el-form-item>

              <!-- 日期选择 -->
              <el-form-item 
                v-else-if="field.type === 'date'"
                :label="field.label" 
                :required="field.required"
                :prop="`field_${field.id}`"
              >
                <el-date-picker 
                  v-model="formModel[`field_${field.id}`]"
                  type="date"
                  :placeholder="field.placeholder"
                  :format="field.format"
                />
                <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
              </el-form-item>

              <!-- 评分 -->
              <el-form-item 
                v-else-if="field.type === 'rating'"
                :label="field.label" 
                :required="field.required"
                :prop="`field_${field.id}`"
              >
                <el-rate 
                  v-model="formModel[`field_${field.id}`]"
                  :max="field.max || 5"
                />
                <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
              </el-form-item>

              <!-- 文件上传 -->
              <el-form-item 
                v-else-if="field.type === 'file'"
                :label="field.label" 
                :required="field.required"
                :prop="`field_${field.id}`"
              >
                <el-upload 
                  class="upload-demo"
                  drag
                  action="#"
                  :auto-upload="false"
                  :accept="field.accept"
                >
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                </el-upload>
                <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
              </el-form-item>
            </div>
          </el-form>
        </div>

        <!-- 提交按钮 -->
        <div v-if="formData.fields.length > 0" class="form-actions">
          <el-button type="primary" size="large" @click="submitForm" :disabled="formData.status !== 1">
            提交表单
          </el-button>
          <p v-if="formData.status !== 1" class="submit-tip">
            表单未发布，无法提交
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { DocumentAdd, UploadFilled } from '@element-plus/icons-vue'
import { getForm } from '@/plugin/gva_intelligent_form/api/form.js'

const route = useRoute()
const router = useRouter()

// 表单数据
const formData = ref({
  title: '',
  description: '',
  fields: [],
  status: 0
})

// 表单模型
const formModel = ref({})
const formRef = ref()

// 复制表单链接
const copyFormLink = async () => {
  const formId = getFormId()
  const link = `${window.location.origin}/#/form/${formId}`
  try {
    await navigator.clipboard.writeText(link)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败，请手动复制：' + link)
  }
}

// 编辑表单
const editForm = () => {
  const formId = getFormId()
  router.push({ name: 'formEditor', query: { id: formId } })
}

// 返回编辑
const goBack = () => {
  const formId = getFormId()
  router.push({ name: 'formEditor', query: { id: formId } })
}

// 提交表单
const submitForm = () => {
  ElMessage.info('这是预览模式，实际提交请访问公开链接')
}

// 获取表单ID（支持从params或query获取）
const getFormId = () => {
  return route.params.id || route.query.id
}

// 表单验证规则
const formRules = ref({})

// 加载表单数据
const loadForm = async () => {
  const formId = getFormId()
  if (formId) {
    try {
      const res = await getForm({ id: parseInt(formId) })
      if (res.code === 0) {
        // 从formConfig中提取fields，确保fields始终是数组
        const formConfig = res.data.formConfig || {}
        const fields = formConfig.fields || []
        
        formData.value = {
          title: res.data.title || '',
          description: res.data.description || '',
          status: res.data.status || 0,
          fields: fields
        }
        
        // 初始化表单模型和验证规则
        const rules = {}
        fields.forEach(field => {
          const fieldKey = `field_${field.id}`
          
          // 初始化表单值
          if (field.type === 'checkbox') {
            formModel.value[fieldKey] = []
          } else if (field.type === 'rating') {
            formModel.value[fieldKey] = 0
          } else if (field.type === 'number') {
            formModel.value[fieldKey] = null
          } else {
            formModel.value[fieldKey] = ''
          }
          
          // 设置验证规则
          if (field.required) {
            rules[fieldKey] = [
              {
                required: true,
                message: `${field.label}为必填项`,
                trigger: field.type === 'checkbox' ? 'change' : 'blur'
              }
            ]
          }
        })
        
        formRules.value = rules
      } else {
        ElMessage.error('获取表单失败：' + (res.msg || '未知错误'))
      }
    } catch (error) {
      ElMessage.error('加载表单失败：' + error.message)
    }
  } else {
    ElMessage.error('表单ID不能为空')
  }
}

onMounted(() => {
  loadForm()
})
</script>

<style scoped>
.form-preview {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 头部工具栏 */
.preview-header {
  background: white;
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.form-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.form-info h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  gap: 12px;
}

/* 预览内容 */
.preview-content {
  padding: 24px;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 表单头部 */
.form-header {
  padding: 40px 40px 32px;
  border-bottom: 1px solid #e4e7ed;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-align: center;
}

.form-header h1 {
  margin: 0 0 16px 0;
  font-size: 32px;
  font-weight: 600;
}

.form-description {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
  line-height: 1.6;
}

/* 表单字段 */
.form-fields {
  padding: 32px 40px;
}

.empty-form {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-form p {
  margin: 16px 0 24px 0;
  font-size: 16px;
}

.field-item {
  margin-bottom: 24px;
}

.field-item.field-half {
  display: inline-block;
  width: 48%;
  margin-right: 4%;
  vertical-align: top;
}

.field-item.field-half:nth-child(2n) {
  margin-right: 0;
}

.field-item.field-third {
  display: inline-block;
  width: 30%;
  margin-right: 5%;
  vertical-align: top;
}

.field-item.field-third:nth-child(3n) {
  margin-right: 0;
}

.field-help {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

/* 表单操作 */
.form-actions {
  padding: 24px 40px 40px;
  text-align: center;
  border-top: 1px solid #f0f0f0;
}

.submit-tip {
  margin: 12px 0 0 0;
  font-size: 14px;
  color: #909399;
}

/* Element Plus 组件样式调整 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

:deep(.el-radio) {
  margin-right: 24px;
  margin-bottom: 8px;
}

:deep(.el-checkbox) {
  margin-right: 24px;
  margin-bottom: 8px;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .preview-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-left {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .form-container {
    margin: 0;
    border-radius: 8px;
  }
  
  .form-header {
    padding: 32px 24px 24px;
  }
  
  .form-header h1 {
    font-size: 24px;
  }
  
  .form-fields,
  .form-actions {
    padding: 24px;
  }
  
  .field-item.field-half,
  .field-item.field-third {
    display: block;
    width: 100%;
    margin-right: 0;
  }
}
</style>